/**
 * @Author: 魏巍
 * @Date:   2018-09-26T02:08:24+08:00
 * @Email:  524314430@qq.com
 * @Filename: check.js
 * @Last modified by:   魏巍
 * @Last modified time: 2018-09-26T02:31:36+08:00
 * @Copyright: free
 */

require('dotenv').config()
const jwt = require('jsonwebtoken')
//检查token是否过期
module.exports = async (ctx, next) => {
  if (ctx.request.header['authorization']) {
    let token = ctx.request.header['authorization'].split(' ')[1]
    //解码token
    let decoded = jwt.decode(token, process.env.JWT_SECRET)
    //console.log(decoded);的输出 ：{ user_id: '123123123', iat: 1494405235, exp: 1494405235 }
    if (token && decoded.exp <= new Date() / 1000) {
      ctx.status = 401
      ctx.body = {
        message: 'token过期'
      }
    } else {
      return next()
    }
  } else {
    ctx.status = 401
    ctx.body = {
      message: '没有token'
    }
  }
}
